package com.lee.boot.head.first.demo.service.impl;

import com.lee.boot.head.first.demo.entity.UserEntity;
import com.lee.boot.head.first.demo.repository.UserRepository;
import com.lee.boot.head.first.demo.service.UserEntityService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;
import java.util.Optional;

/**
 * @Auther: Lee
 * @Date: 2018/6/6 11:08
 * @Description:
 */
//该注解是用来开启声明的类参与缓存,如果方法内的@Cacheable注解没有添加key值，那么会自动使用cahceNames配置参数并且追加方法名
@CacheConfig(cacheNames = "user")
@Service
public class UserEntityServiceImpl implements UserEntityService {
    @Autowired
    private UserRepository userRepository;


    //配置方法的缓存参数，可自定义缓存的key以及value
//    @Cacheable
    @Override
    public List<UserEntity> findAll() {
        return userRepository.findAll();
    }

    @Override
    public void delete(Long id) {

        userRepository.deleteById(id);
    }

    @Override
    public UserEntity add(UserEntity userEntity) {
        return userRepository.save(userEntity);
    }

    public void add(String a, String b, Integer c, char d) {

    }

    public String add() {
        return null;
    }

    @Override
    public UserEntity update(UserEntity userEntity) {
        return userRepository.save(userEntity);
    }

    @Override
    public Optional<UserEntity> get(String name) {
        return userRepository.findOne(new Specification<UserEntity>() {
            @Override
            public Predicate toPredicate(Root<UserEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                criteriaQuery.where(criteriaBuilder.equal(root.get("name"), name));
                return null;
            }
        });
    }

    @Override
    public List<UserEntity> getByName(String name) {
        return userRepository.selectByUsername(name);
    }
}

